// Copyright 2013 Petar Maymounkov
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package ripple

import (
	"io"
	"os"
	"strconv"
	"sync"

	"circuit/kit/rh"
)

func MustDupFID(fid rh.FID) rh.FID {
	_fid, err := fid.Walk(nil)
	if err != nil {
		panic(err)
	}
	return _fid
}

func uid() string {
	return strconv.Itoa(os.Getuid())
}

func gid() string {
	return strconv.Itoa(os.Getgid())
}

func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}

func runOnClose(r io.Reader, f func()) io.ReadCloser {
	var once sync.Once
	return &roc{
		Reader: r,
		roc: func() {
			if f != nil {
				once.Do(f)
			}
		},
	}
}

type roc struct {
	io.Reader
	roc func()
}

func (r *roc) Close() error {
	r.roc()
	return nil
}
